package cn.itsource.system.service.impl;

import cn.itsource.org.domain.Department;
import cn.itsource.system.domain.Menu;
import cn.itsource.system.mapper.MenuMapper;
import cn.itsource.system.service.IMenuService;
import cn.itsource.basic.base.service.impl.BaseServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author h
 * @since 2023-07-14
 */
@Service
public class MenuServiceImpl extends BaseServiceImpl<Menu> implements IMenuService {

    @Autowired
    private MenuMapper menuMapper;

    @Override
    public List<Menu> menuTree() {
        //查询出所有的dept
        List<Menu> menus = menuMapper.loadAll();

        //把所有数据转换成map，key是自己的id，value是自己这个对象
        Map<Long, Menu> map = menus.stream().collect(Collectors.toMap(Menu::getId, menu -> menu));
        //结果集
        List<Menu> results = new ArrayList<>();
        for (Menu menu : menus) {
            //找出所有的顶级部门
            if(menu.getParentId() == null){
                //把顶级部门装到集合中
                results.add(menu);
            }else{
                Menu dadMenu = map.get(menu.getParentId());
                if(dadMenu != null){
                    dadMenu.getChildren().add(menu);
                }

            }
        }
        return results;
    }
}
